<script lang="ts" setup>
import { onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useArticleMultipleStore } from '@/stores/articleMultipleStore';
import ArticleListLayout from "@/layouts/ArticleListLayout.vue";
import ArticleListPagination from "@/components/pageElement/ArticleListPagination.vue";
import { formatDate } from "@/utils/tools";

const props = withDefaults(defineProps<{
  names: string[];
  isPdf?: boolean;
}>(), {
  isPdf: false
});

const route = useRoute();
const articleMultipleStore = useArticleMultipleStore();

// 初始化分类并加载当前页
articleMultipleStore.setCategories(props.names);

onMounted(async () => {
  for (const name of props.names) {
    const pageQuery = route.query[`page_${name}`];
    const page = pageQuery ? parseInt(pageQuery as string, 10) : articleMultipleStore.categories[name]?.currentPage || 1;

    await articleMultipleStore.loadArticles(name, page);

    const articleId = parseInt(route.query[`articleId_${name}`] as string, 10);
    if (articleId) {
      await articleMultipleStore.setCurrentArticleIndex(name, articleId);
      await articleMultipleStore.loadPrevNextPages(name);
    }
  }
});

const handlePageChange = async (categoryName: string, newPage: number) => {
  await articleMultipleStore.loadArticles(categoryName, newPage);
  const newQuery = {
    ...route.query,
    [`page_${categoryName}`]: newPage,
  };
  const queryString = new URLSearchParams(newQuery as any).toString();
  window.history.pushState({}, "", `${route.path}?${queryString}`);
};

</script>

<template>
  <article-list-layout>
    <el-collapse>
      <el-collapse-item v-for="name in names" :title="name" :name="name" :key="name">
        <div id="article_list">
          <ul class="listrx">
            <li v-for="(article) in articleMultipleStore.categories[name].articleList" :key="article.id">
              <h6 class="fr">{{ formatDate(article.createTime) }}</h6>
              <NuxtLink
                  :title="article.title"
                  :to="{ name: isPdf ? n2r('PDF文章') : n2r('常规文章'), query: { [`articleId_${name}`]: article.id } }"
                  @click="setLocationByName('捐赠名单')"
              > <!--不展示隐藏分类，这里写死-->
                {{ article.title }}
              </NuxtLink>
            </li>
          </ul>
          <article-list-pagination
              :current-page="articleMultipleStore.categories[name].currentPage"
              :total-pages="Math.ceil(articleMultipleStore.categories[name].articleList.length / articleMultipleStore.categories[name].pageSize)"
              @change="(newPage) => handlePageChange(name, newPage)"
          />
        </div>
      </el-collapse-item>
    </el-collapse>
  </article-list-layout>
</template>
